import React from 'react'
import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import { Button, Fab, FormLabel, TextField, Tooltip, ListItem, Radio } from '@material-ui/core'
import { makeStyles } from '@material-ui/core/styles';
import { Search, Loop, Add, Delete, BorderColor, GetApp, RecentActorsRounded } from '@material-ui/icons';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogActions from '@material-ui/core/DialogActions';
import Snackbar from '@material-ui/core/Snackbar';
import PubSub from 'pubsub-js'
import { set } from 'js-cookie';
import { nanoid } from 'nanoid'

import { download } from '../../../../uitl/ruoyi'
import { delPost, exportPost, getPost, addPost, updatePost } from '../../../../api/system/post'

const useStyles = makeStyles((theme) => ({
    root: {
        '& > *': {
            margin: theme.spacing(2),
        },
        marginTop: '10px',
    },
    //功能按钮
    left: {
        float: 'left'
    },
    right: {
        float: "right",
    },
    //新增按钮
    btnInsert: {
        minWidth: '60px',
        '&:hover': {
            backgroundColor: 'blue',
            color: 'white',
        }
    },
    //修改按钮
    btnUpdate: {
        marginLeft: '15px',
        color: 'lightgreen',
        minWidth: '60px',
        border: '1px solid lightgreen',
        '&:hover': {
            backgroundColor: 'lightgreen',
            color: 'white',
        }
    },
    //删除按钮
    btnDelete: {
        marginLeft: '15px',
        minWidth: '60px',
        '&:hover': {
            backgroundColor: 'red',
            color: 'white',
        }
    },
    //导出按钮
    btnGetApp: {
        color: 'orange',
        border: '1px solid orange',
        marginLeft: '15px',
        minWidth: '60px',
        '&:hover': {
            backgroundColor: 'orange',
            color: 'white',
        }
    },
    //隐藏搜索
    btnHide: {
        border: '1px solid lightgray',
        backgroundColor: 'white',
        color: 'lightgray',
        '&:hover': {
            backgroundColor: 'lightblue',
            border: '1px solid lightblue',
            color: 'white'
        }
    },
    //刷新按钮
    btnRefresh: {
        marginLeft: '15px',
        border: '1px solid lightgray',
        backgroundColor: 'white',
        color: 'lightgray',
        '&:hover': {
            backgroundColor: 'lightblue',
            border: '1px solid lightblue',
            color: 'white'
        }
    }
}));

export default function Dictionary() {
    const classes = useStyles();
    const [open, setOpen] = React.useState(false);  //新增
    const [selectedValue, setselectedValue] = React.useState(0);   // 单选框 初始
    const [shuzi, setshuzi] = React.useState([]);  //获取数据点击的数组 Id
    const [sanchuanddaochu, setshuchu] = React.useState(true); //删除和导出按钮能不能点击初始值
    const [xiugai, setxiugai] = React.useState(true); //修改按钮能不能点击初始值
    const [xianshiyingchang, setxianshuyingchang] = React.useState(false);

    React.useEffect(() => {
        const token = PubSub.subscribe('PengYe', (_, stateObj) => {
            setshuzi(stateObj.selected)
        })
        return () => {
            PubSub.unsubscribe(token)
        }
    }, [])
    React.useEffect(() => {
        if (shuzi.length == 1) {
            setshuchu(false)
            setxiugai(false)
        } else if (shuzi.length > 1) {
            setxiugai(true)
        } else {
            setshuchu(true)
            setxiugai(true)
        }
    }, [shuzi])


    const handleChange = (event) => {
        setselectedValue(event.target.value);
    };
    const handleClose = () => {
        setOpen(false);
    };

    //  消息框
    const [xiaoxikuangneirong, setxiaoxikuangneirong] = React.useState("删除成功！")


    //   警告框
    const [sanchu, setsanchu] = React.useState(false);
    const [feikongzhuangtai, setfeikongzhuangtai] = React.useState({ postName: false, postCode: false, postSort: false }); //非空的

    //  弹出消息框
    const [xiaoxitan, setxiaoxitan] = React.useState(false);
    const sanchuanniuchu = () => {
        setsanchu(true);
    };
    const sanchuClose = () => {
        setsanchu(false);
    };
    //删除
    const handleDelete = (postIds) => {
        delPost(postIds).then(
            response => {
                setshuzi([]);
                setxiaoxikuangneirong("删除成功！")
                setsanchu(false);
                setxiaoxitan(true);
                PubSub.publish('ShuXin', 1);
                console.log('删除成功了', response);
                setInterval(() => {
                    setxiaoxitan(false);
                }, 3000)

            },
            error => {
                setxiaoxikuangneirong("删除失败！")
                setsanchu(false);
                setxiaoxitan(true);
                setInterval(() => {
                    setxiaoxitan(false);
                }, 3000)
                console.log("失败了", error)

            }
        )
    };

    //以上

    //导出
    const postdaochu = () => {
        if (window.confirm("确实全部导出吗？")) {
            exportPost().then(
                response => {
                    console.log('成功了', response);
                    download(response.msg)
                    setxiaoxikuangneirong("导出成功！")
                    setxiaoxitan(true);
                    setInterval(() => {
                        setxiaoxitan(false);
                    }, 3000)
                },
                error => {
                    setxiaoxikuangneirong("导出失败！")
                    setxiaoxitan(true);
                    setInterval(() => {
                        setxiaoxitan(false);
                    }, 3000)
                    console.log("失败了", error)
                }
            )
        }

    };

    //弹出是添加还是修改框
    const [tianjiaxiugaidianji, settianjiaxiugaidianji] = React.useState(0);


    //修改的初始值
    const [huoqutianjiazi, sethuoqutianjiazi] = React.useState({ postName: '', postCode: '', postSort: '', status: selectedValue, remark: '' });
    const [tianjiaxiugaidezi, settianjiaxiugaizi] = React.useState('添加岗位')
    const postXiugaianniu = (id) => {
        settianjiaxiugaizi("修改岗位")
        settianjiaxiugaidianji(1);
        getPost(id).then(
            response => {
                console.log('成功了', response.data)
                sethuoqutianjiazi(response.data)
                setselectedValue(response.data.status)
                setOpen(true);
            },
            error => {
                console.log("失败了", error)
                window.alert("按ID查询失败")
            }
        );
    };
    //添加
    const handleClickOpen = () => {
        sethuoqutianjiazi({ postName: '', postCode: '', postSort: '0', status: '0', remark: '' })
        settianjiaxiugaidianji(0);
        setOpen(true);
    };

    //新增修改获取值方法
    const getVlaue = (key, e) => {
        let d = huoqutianjiazi
        for (let index in huoqutianjiazi) {
            if (index === key) {
                d[index] = e.target.value
                sethuoqutianjiazi(d)
            }
        }
    }

    // 是否需要修改
    const [xiugaideyigeid, setxiugaideyigeid] = React.useState();
    React.useEffect(() => {
        const token = PubSub.subscribe('ShujuxiugaideId', (_, id) => {
            setxiugaideyigeid(id);
        })
        if(xiugaideyigeid==null){

        }else{
            postXiugaianniu(xiugaideyigeid);
        }
        
    }, [xiugaideyigeid])

    //修改方法
    const find = () => {
        let d = huoqutianjiazi;
        d['status'] = selectedValue;
        sethuoqutianjiazi(d)
        if (huoqutianjiazi.postName === '' || huoqutianjiazi.postCode === '' || huoqutianjiazi.postSort < 1) {
            if (huoqutianjiazi.postName === '') {
                setxiaoxikuangneirong("岗位名称不能为空！")
                setxiaoxitan(true);
                setInterval(() => {
                    setxiaoxitan(false);
                }, 3000);
            }
            if (huoqutianjiazi.postCode === '') {
                setxiaoxikuangneirong("岗位编码不能为空！")
                setxiaoxitan(true);
                setInterval(() => {
                    setxiaoxitan(false);
                }, 3000);
            }
            if (huoqutianjiazi.postSort < 1) {
                setxiaoxikuangneirong("顺序不能小于0！")
                setxiaoxitan(true);
                setInterval(() => {
                    setxiaoxitan(false);
                }, 3000);
            }
        } else {
            updatePost(huoqutianjiazi).then(
                response => {
                    setxiaoxikuangneirong("修改成功！")
                    console.log('修改成功了', response)
                    setOpen(false);
                    setxiaoxitan(true);
                    setInterval(() => {
                        setxiaoxitan(false);
                    }, 3000)
                    PubSub.publish('ShuXin', 1);

                },
                error => {
                    console.log("失败了", error)
                    setxiaoxikuangneirong("修改失败！")
                    setOpen(false);
                    setxiaoxitan(true);
                    setInterval(() => {
                        setxiaoxitan(false);
                    }, 3000)
                }
            );

        }
    }
    //添加方法
    const addfind = () => {

        let d = huoqutianjiazi;
        d['status'] = selectedValue;
        sethuoqutianjiazi(d)

        //文本框动态的变红
        // let py=feikongzhuangtai;
        // if(huoqutianjiazi.postName===''){
        //     py['postName']=true;
        // }
        // if(huoqutianjiazi.postCode===''){
        //     py['postCode']=true;
        // }
        // if(huoqutianjiazi.postSort<1){
        //     py['postSort']=true;
        // }
        // setfeikongzhuangtai(py);

        if (huoqutianjiazi.postName === '' || huoqutianjiazi.postCode === '' || huoqutianjiazi.postSort < 1) {
            if (huoqutianjiazi.postName === '') {
                setxiaoxikuangneirong("岗位名称不能为空！")
                setxiaoxitan(true);
                setInterval(() => {
                    setxiaoxitan(false);
                }, 3000);
            }
            if (huoqutianjiazi.postCode === '') {
                setxiaoxikuangneirong("岗位编码不能为空！")
                setxiaoxitan(true);
                setInterval(() => {
                    setxiaoxitan(false);
                }, 3000);
            }
            if (huoqutianjiazi.postSort < 1) {
                setxiaoxikuangneirong("顺序不能小于0！")
                setxiaoxitan(true);
                setInterval(() => {
                    setxiaoxitan(false);
                }, 3000);
            }
        } else {
            addPost(huoqutianjiazi).then(
                response => {
                    setxiaoxikuangneirong("添加成功！")
                    console.log('添加成功了', response)
                    setOpen(false);
                    setxiaoxitan(true);
                    setInterval(() => {
                        setxiaoxitan(false);
                    }, 3000)
                    PubSub.publish('ShuXin', 1);

                },
                error => {
                    console.log("失败了", error)
                    setxiaoxikuangneirong("添加失败！")
                    setOpen(false);
                    setxiaoxitan(true);
                    setInterval(() => {
                        setxiaoxitan(false);
                    }, 3000)
                }
            );

        }


    }



    return (
        <div className={classes.root}>
            <div className={classes.left}>
                <Button className={classes.btnInsert} onClick={handleClickOpen} variant="outlined" color="primary">
                    <Add />新增
                </Button>

                <Dialog open={open} onClose={handleClose}>
                    <DialogTitle><h2>{tianjiaxiugaidezi}</h2></DialogTitle>
                    <DialogContent>
                        <ListItem>
                            <FormLabel style={{ color: 'red' }}>*</FormLabel>
                            <FormLabel style={{ color: 'black', marginRight: '15px', minWidth: '70px' }}>岗位名称</FormLabel>
                            <TextField
                                style={{ minWidth: '400px' }}
                                variant='outlined'
                                placeholder='请输入岗位名称'
                                name="postName"
                                size='small'
                                defaultValue={huoqutianjiazi.postName}
                                error={feikongzhuangtai.postName}
                                onKeyUp={getVlaue.bind(this, 'postName')}

                            ></TextField>
                        </ListItem>
                        <ListItem style={{ marginTop: '15px' }}>
                            <FormLabel style={{ color: 'red' }}>*</FormLabel>
                            <FormLabel style={{ color: 'black', marginRight: '15px', minWidth: '70px' }}>岗位编码</FormLabel>
                            <TextField
                                style={{ minWidth: '400px' }}
                                variant='outlined'
                                placeholder='请输入编码名称'
                                name="postCode"
                                defaultValue={huoqutianjiazi.postCode}
                                error={feikongzhuangtai.postCode}
                                size='small'
                                onKeyUp={getVlaue.bind(this, 'postCode')}

                            >
                            </TextField>
                        </ListItem>
                        <ListItem style={{ marginTop: '15px' }}>
                            <FormLabel style={{ color: 'red' }}>*</FormLabel>
                            <FormLabel style={{ color: 'black', marginRight: '15px', minWidth: '70px' }}>岗位顺序</FormLabel>
                            <TextField
                                id="outlined-number"
                                style={{ minWidth: '400px' }}
                                defaultValue={huoqutianjiazi.postSort}
                                error={feikongzhuangtai.postSort}
                                type="number"
                                InputLabelProps={{
                                    shrink: true,
                                }}
                                variant="outlined"
                                name="postSort"
                                onChange={getVlaue.bind(this, 'postSort')}

                            />
                        </ListItem>
                        <ListItem>
                            <FormLabel style={{ color: 'black', marginLeft: '40px', minWidth: '40px' }}>状态</FormLabel>
                            <Radio
                                checked={selectedValue == 0}
                                onChange={handleChange}
                                value="0"
                                name="status"
                            />
                            <FormLabel>正常</FormLabel>
                            <Radio
                                checked={selectedValue == 1}
                                onChange={handleChange}
                                value="1"
                                name="status"
                            />
                            <FormLabel>停用</FormLabel>
                        </ListItem>
                        <ListItem>
                            <FormLabel style={{ color: 'black', marginLeft: '40px', minWidth: '50px' }}>备注</FormLabel>
                            <TextField
                                style={{ minWidth: '400px' }}
                                variant='outlined'
                                placeholder='请输入备注'
                                size='medium'
                                name="remark"
                                defaultValue={huoqutianjiazi.remark}
                                onChange={getVlaue.bind(this, 'remark')}
                            ></TextField>
                        </ListItem>
                        <ListItem style={{ marginTop: '15px', marginBottom: '15px' }}>
                            <Button style={{ marginLeft: '350px' }} onClick={tianjiaxiugaidianji === 0 ? addfind : find} variant="contained" color="primary">
                                确定
                            </Button>
                            <Button style={{ marginLeft: '15px' }} onClick={handleClose} variant="contained" >
                                取消
                            </Button>
                        </ListItem>
                    </DialogContent>
                </Dialog>


                <Button className={classes.btnUpdate} onClick={()=>postXiugaianniu(shuzi[0])} disabled={xiugai} variant="outlined">
                    <BorderColor />修改
                </Button>
                <Button onClick={sanchuanniuchu} className={classes.btnDelete} disabled={sanchuanddaochu} variant="outlined" color="secondary">
                    <Delete />删除
                </Button>
                <Dialog
                    open={sanchu}
                    onClose={sanchuClose}
                    aria-labelledby="alert-dialog-title"
                    aria-describedby="alert-dialog-description"
                >
                    <DialogTitle id="alert-dialog-title" >删除数据 {shuzi.map((py) => { return `${py} ` })}</DialogTitle>
                    <DialogContent>
                        <DialogContentText id="alert-dialog-description">
                            确定删除编号：{shuzi.map((py) => { return `${py} ` })} ,  这{shuzi.length}条记录吗?
                            请不要瞎搞！！！！！
                        </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={sanchuClose} color="primary">
                            取消
                        </Button>
                        <Button onClick={(event) => handleDelete(shuzi)} color="primary" autoFocus>
                            同意
                        </Button>
                    </DialogActions>
                </Dialog>
                <Snackbar
                    anchorOrigin={{ vertical: 'top', horizontal: 'center', }}
                    open={xiaoxitan}
                    message={xiaoxikuangneirong}
                    key={nanoid()}
                />
                <Button onClick={postdaochu} className={classes.btnGetApp} variant="outlined" >
                    <GetApp />导出
                </Button>
            </div>
            <div className={classes.right}>
                <Tooltip title={xianshiyingchang ? '显示搜索' : '隐藏搜索'} placement="top" onClick={() => { setxianshuyingchang(!xianshiyingchang); PubSub.publish('xianshiyingchang', { xianshiyingchang }) }}>
                    <Fab className={classes.btnHide} size='small' variant='circular'>
                        <Search />
                    </Fab>
                </Tooltip>
                <Tooltip title="刷新" placement="top" onClick={() => { PubSub.publish('ShuXin', 1); PubSub.publish('TiaoJian', []) }}>
                    <Fab className={classes.btnRefresh} size='small' variant='circular'>
                        <Loop />
                    </Fab>
                </Tooltip>
            </div>
        </div>
    )
}


